package com.zcc.blog.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.SecureUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zcc.blog.dto.PasswordDto;
import com.zcc.blog.entity.User;
import com.zcc.blog.mapper.UserMapper;
import com.zcc.blog.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zcc.blog.untils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zcc
 * @since 2022-09-05
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;

    @Override
    public Result register(User user) {
        User temp = new User();
        temp.setAvatar("https://zzzzzzzzzzzzzzzzzzzzzzzzz.oss-cn-hangzhou.aliyuncs.com/QQ%E5%9B%BE%E7%89%8720220913164733.jpg");
        temp.setCreated(LocalDateTime.now());
        temp.setLastLogin(null);
        temp.setStatus(0);
        temp.setPassword(SecureUtil.md5(user.getPassword()));
        BeanUtil.copyProperties(user,temp,"id", "avatar", "created", "lastLogin", "status", "password");
        boolean save = this.save(temp);
        if (save) {
            return Result.success(null);
        }
        return Result.fail("注册失败");
    }

    @Override
    public Result updateAvatar(Long id, MultipartFile avatar) {
        // yourEndpoint填写Bucket所在地域对应的Endpoint。以华东1（杭州）为例，Endpoint填写为https://oss-cn-hangzhou.aliyuncs.com。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = "LTAI5tRBjfZigqCdWCVYwrQK";
        String accessKeySecret = "eogSM9YsYyJaAXkmr11EsJYkwPp4EN";
        String bucketName = "zzzzzzzzzzzzzzzzzzzzzzzzz";
        String fileName = avatar.getOriginalFilename();
        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
            InputStream inputStream = avatar.getInputStream();
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();
        } catch (Exception e){
            return Result.fail(e.getMessage());
        }
        String url = "https://zzzzzzzzzzzzzzzzzzzzzzzzz.oss-cn-hangzhou.aliyuncs.com/" + fileName;
        boolean b = userMapper.updateAvatar(url, id);
        if (b) {
            return Result.success(url);
        }
        return Result.fail("更新头像失败");
    }

    @Override
    public boolean updateLastLogin(Long id) {
        return userMapper.updateLastLogin(LocalDateTime.now(), id);
    }

    @Override
    public Result updateUserInfo(User user) {
        boolean update = this.update(user, new QueryWrapper<User>().eq("id", user.getId()));
        if (update) {
            return Result.success(null);
        }
        return Result.fail("更新基本信息失败");
    }

    @Override
    public Result updatePassword(PasswordDto passwordDto) {
        Long id = passwordDto.getId();
        System.out.println(passwordDto);
        String oPassword = passwordDto.getOPassword();
        User user = this.userMapper.selectById(id);
        if (Objects.equals(user.getPassword(), SecureUtil.md5(oPassword))) {
            String nPassword = passwordDto.getPassword();
            String password = SecureUtil.md5(nPassword);
            boolean b = userMapper.updatePasswordBoolean(password, id);
            if (b) {
                return Result.success(null);
            }
        }
        return Result.fail("与原始密码不符");
    }

    @Override
    public User getUserById(Long id) {
        User user = this.userMapper.selectById(id);
        return user;
    }

}
